﻿Imports System.IO
Imports System.Data.SQLite

Public Class DBOps
    ' Global because you create it in the ImportGEDb3 and use it in the SaveGEDB3 '
    Private daImport As SQLiteDataAdapter

    Public Function ImportGEDb3(Filepath As String, Dtable As String) As DataTable
        Dim dt As New DataTable("Data")
        daImport = New SQLiteDataAdapter("Select * from " & Dtable, "Data Source='" & Filepath & "'")
        daImport.Fill(dt)

        ' This is critical, it is the SQLiteCommandBuilder that takes '
        ' the SQLiteDataAdapter SELECT statement and builds the required'
        ' INSERT,UPDATE,DELETE commands.'
        Dim builder = New SQLiteCommandBuilder(daImport)
        Return dt
    End Function

    Public Function SelectFromGEDb3(Filepath As String, Dtable As String, DSelect As String, DQuery As String) As DataTable
        Dim dt As New DataTable("Data")
        daImport = New SQLiteDataAdapter("Select " & DSelect & " from " & Dtable & " " & DQuery,
                                         "Data Source='" & Filepath & "'")
        daImport.Fill(dt)

        ' This is critical, it is the SQLiteCommandBuilder that takes '
        ' the SQLiteDataAdapter SELECT statement and builds the required'
        ' INSERT,UPDATE,DELETE commands.'
        Dim builder = New SQLiteCommandBuilder(daImport)
        Return dt
    End Function

    Public Sub SaveGEDb3(dt As DataTable)
        Try
            If daImport IsNot Nothing Then
                daImport.Update(dt)
            End If
        Catch
        End Try
    End Sub

    Public Shared Function NotNull(Of T)(ByVal Value As T, ByVal DefaultValue As T) As T

        If Value Is Nothing OrElse IsDBNull(Value) Then
            Return DefaultValue
        Else
            Return Value
        End If
    End Function

End Class